#include "event/loop.hpp"
#include "fmt/core.h"
#include "network/sockaddr.hpp"
#include "network/tcp_acceptor.hpp"
#include "network/tcp_connection.hpp"

#include <set>

using namespace std;
using namespace ibox::event;
using namespace ibox::network;
int main() {
    SockAddr bind_addr = SockAddr::from_string("127.0.0.1:8080");
    auto loop = Loop();

    // 这个例子中是用的TcpAcceptor, 不是TcpServer管理Connection,
    // 所以有手动管理Tcp连接的步骤
    TcpAcceptor acceptor{&loop};
    acceptor.initialize(bind_addr, 1);
    acceptor.set_new_connection_callback([&](TcpConnection *new_conn) {
        // 注意new_conn指针使用值传递方式
        new_conn->set_disconnected_callback([=]() {
            fmt::print("connection disconnected: {} !!!\n",
                       new_conn->peer_addr()->to_string());
            delete new_conn;
        });
        new_conn->bind(new_conn); // 信息流绑定为自己
    });
    acceptor.start();

    if (bind_addr.type() == SockAddr::Type::IPv4) {
        IpAddress ip;
        uint16_t port = 0;
        bind_addr.get(ip, port);
        cout << "try command: nc " << ip.to_string() << ' ' << port << '\n';
    }
    loop.run();
}
